﻿
@{
    ViewData["Title"] = "BOM详情";
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/layui@2.9.8/dist/css/layui.css">
<script src="https://unpkg.com/layui@2.9.8/dist/layui.js"></script>

<style>
    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background-color: #f8f9fa;
    }

    .container-fluid {
        padding: 20px;
    }

    .nav-tabs .nav-link {
        color: #495057;
        border: 1px solid transparent;
        border-top-left-radius: .25rem;
        border-top-right-radius: .25rem;
        font-weight: 500;
    }

    .nav-tabs .nav-link.active {
        color: #0d6efd;
        background-color: #fff;
        border-color: #dee2e6 #dee2e6 #fff;
        border-bottom: 3px solid #0d6efd;
    }

    .card {
        border: none;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        margin-top: 20px;
    }

    .card-header {
        background-color: #fff;
        border-bottom: 1px solid #e9ecef;
        padding: 1rem 1.5rem;
    }

    .table thead th {
        background-color: #e9ecef;
        font-weight: 600;
        color: #495057;
        text-align: center;
    }

    .table tbody tr:hover {
        background-color: #f2f2f2;
    }

    .table tbody td {
        text-align: center;
        vertical-align: middle;
    }

    .pagination .page-item.active .page-link {
        background-color: #0d6efd;
        border-color: #0d6efd;
    }

    .pagination .page-link {
        color: #0d6efd;
    }

    .form-control:focus {
        border-color: #86b7fe;
        box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
    }

    .btn-primary {
        background-color: #0d6efd;
        border-color: #0d6efd;
    }

    .btn-primary:hover {
        background-color: #0b5ed7;
        border-color: #0a58ca;
    }

    .btn-outline-secondary {
        border-color: #6c757d;
        color: #6c757d;
    }

    .btn-outline-secondary:hover {
        background-color: #6c757d;
        border-color: #6c757d;
        color: #fff;
    }

    .info-section {
        background-color: #fff;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        margin-bottom: 20px;
    }

    .info-section h5 {
        color: #0d6efd;
        margin-bottom: 15px;
        font-weight: 600;
    }

    .form-label {
        font-weight: 500;
        color: #495057;
    }

    .form-control, .form-select {
        border-radius: 6px;
        border: 1px solid #ced4da;
    }

    .form-control:focus, .form-select:focus {
        border-color: #86b7fe;
        box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
    }

    .action-buttons {
        margin-top: 20px;
        text-align: center;
    }

    .action-buttons .btn {
        margin: 0 10px;
        padding: 8px 20px;
        border-radius: 6px;
    }

    .tab-content {
        padding: 20px 0;
    }

    .search-export-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding: 15px;
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .search-box {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .search-box input {
        width: 300px;
        border-radius: 20px;
        padding: 8px 15px;
    }

    .search-box button {
        border-radius: 20px;
        padding: 8px 15px;
    }
</style>

<div class="container-fluid">
    <!-- 页面标题和操作按钮 -->
    <div class="info-section">
        <div class="row">
            <div class="col-md-8">
                <h3 id="pageTitle">新产品新产品新产品BOM</h3>
                <div class="row mt-3">
                    @* <div class="col-md-6">
                        <small class="text-muted">创建人: 赵五六</small><br>
                        <small class="text-muted">创建时间: 2025-01-13 16:35:30</small>
                    </div>
                    <div class="col-md-6">
                        <small class="text-muted">最后修改人: 赵五六</small><br>
                        <small class="text-muted">修改时间: 2022-06-07 19:49:12</small>
                    </div> *@
                </div>
            </div>
            <div class="col-md-4">
              @*   <div class="action-buttons">
                    <button class="btn btn-primary">编辑</button>
                    <button class="btn btn-danger">删除</button>
                    <button class="btn btn-info">打印</button>
                    <button class="btn btn-warning">展开结构</button>
                </div> *@
            </div>
        </div>
    </div>

    <!-- Navigation Tabs -->
    <ul class="nav nav-tabs mb-3" id="bomTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="bom-info-tab" data-bs-toggle="tab" data-bs-target="#bom-info" type="button" role="tab" aria-controls="bom-info" aria-selected="true">BOM信息</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="bom-accessories-tab" data-bs-toggle="tab" data-bs-target="#bom-accessories" type="button" role="tab" aria-controls="bom-accessories" aria-selected="false">BOM配件</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="process-flow-tab" data-bs-toggle="tab" data-bs-target="#process-flow" type="button" role="tab" aria-controls="process-flow" aria-selected="false">工艺流程</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="operation-record-tab" data-bs-toggle="tab" data-bs-target="#operation-record" type="button" role="tab" aria-controls="operation-record" aria-selected="false">操作记录</button>
        </li>
    </ul>

    <!-- Tab Content -->
    <div class="tab-content" id="bomTabContent">
        <!-- BOM信息 Tab -->
        <div class="tab-pane fade show active" id="bom-info" role="tabpanel" aria-labelledby="bom-info-tab">
            <div class="row">
                <div class="col-md-6">
                    <div class="info-section">
                        <h5>◆ 基础信息</h5>
                        <div class="mb-3">
                            <label class="form-label">BOM编号</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="bomNumber"  readonly />
                                <div class="input-group-text">
                                    <input type="checkbox" id="systemNumber" checked />
                                    <label class="ms-2 mb-0" for="systemNumber">系统编号</label>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">默认BOM</label>
                            <select class="form-select" id="defaultBOM">
                                <option value="false">否</option>
                                <option value="true">是</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">成品类型</label>
                            <select class="form-select" id="productType">
                                <option value="类型一" selected>类型一</option>
                                <option value="类型二">类型二</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">日产量</label>
                            <input type="text" class="form-control" id="dailyOutput" value="50" />
                        </div>
              @*           <div class="mb-3">
                            <label class="form-label">预估成本</label>
                            <input type="text" class="form-control" id="estimatedCost" value="8,000" readonly />
                        </div> *@
                        <div class="mb-3">
                            <label class="form-label">备注</label>
                            <textarea class="form-control" id="remarks" rows="3"></textarea>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="info-section">
                        <h5>◆ 产品详情</h5>
                        <div class="mb-3">
                            <label class="form-label">BOM主题</label>
                            <input type="text" class="form-control" id="bomTheme" value="产品lampBOM" />
                        </div>
                        <div class="mb-3">
                            <label class="form-label">版本</label>
                            <input type="text" class="form-control" id="version" value="1.1" />
                        </div>
                        <div class="mb-3">
                            <label class="form-label">成品名称</label>
                            <input type="text" class="form-control" id="productName" value="lamp" />
                        </div>
                  @*       <div class="mb-3">
                            <label class="form-label">当前库存</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="currentInventory" value="500" readonly />
                                <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                    <i class="layui-icon layui-icon-down"></i>
                                </button>
                                <ul class="dropdown-menu">
                                    <li><a class="dropdown-item" href="#">本地: 60</a></li>
                                    <li><a class="dropdown-item" href="#">仓库二: 0</a></li>
                                    <li><a class="dropdown-item" href="#">仓库三: 0</a></li>
                                    <li><a class="dropdown-item" href="#">物料仓库一: 0</a></li>
                                    <li><a class="dropdown-item" href="#">新产品仓库: 0</a></li>
                                </ul>
                            </div>
                        </div> *@
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12 text-center">
                    <button type="button" class="btn btn-success" id="confirmBtn" onclick="UpdateBom()">确定</button>
                </div>
            </div>
        </div>

        <!-- BOM配件 Tab -->
        <div class="tab-pane fade" id="bom-accessories" role="tabpanel" aria-labelledby="bom-accessories-tab">
            <div class="search-export-bar">
                <button id="exportAccessoriesBtn" class="btn btn-primary" onclick="DaochuAccessories()">导出</button>
                <div class="search-box">
                    <input type="text" id="searchAccessoriesInput" class="form-control" placeholder="请搜索">
                    <button class="btn btn-outline-secondary" type="button" id="searchAccessoriesBtn">
                        <i class="layui-icon layui-icon-search"></i>
                    </button>
                </div>
            </div>
            
            <div class="card">
                <div class="card-body">
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th style="width: 40px;"><input type="checkbox" id="selectAllAccessories"></th>
                                <th style="width: 60px;">序号</th>
                                <th>物品编号</th>
                                <th>物品名称</th>
                                <th>规格型号</th>
                                <th>单位</th>
                                <th>品牌</th>
                                <th>配件数量</th>
                                <th>损耗率</th>
                             @*    <th>当前库存</th>
                                <th>可供生产</th> *@
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="accessoriesTableBody">
                            <!-- 数据将通过AJAX加载 -->
                        </tbody>
                    </table>
                    
                    <div class="d-flex justify-content-between align-items-center mt-3">
                        <div id="totalAccessoriesInfo">共 0 项数据</div>
                        <div class="d-flex align-items-center">
                            <select id="accessoriesPageSizeSelect" class="form-select form-select-sm me-2" style="width: auto;">
                                <option value="5" selected>5条/页</option>
                                <option value="10">10条/页</option>
                                <option value="20">20条/页</option>
                                <option value="50">50条/页</option>
                            </select>
                            <div id="accessoriesLaypageContainer"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 工艺流程 Tab -->
        <div class="tab-pane fade" id="process-flow" role="tabpanel" aria-labelledby="process-flow-tab">
            <div class="search-export-bar">
                <button id="exportProcessBtn" class="btn btn-primary" onclick="DaochuProcess()">导出</button>
                <div class="search-box">
                    <input type="text" id="searchProcessInput" class="form-control" placeholder="请输入">
                    <button class="btn btn-outline-secondary" type="button" id="searchProcessBtn">
                        <i class="layui-icon layui-icon-search"></i>
                    </button>
                </div>
            </div>
            
            <div class="card">
                <div class="card-body">
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th style="width: 40px;"><input type="checkbox" id="selectAllProcess"></th>
                                <th style="width: 60px;">序号</th>
                                <th>工序编码</th>
                                <th>工序名称</th>
                                <th>加工顺序</th>
                                <th>工艺流程</th>
                                <th>负责人</th>
                                <th>部门</th>
                                <th>单位工作量</th>
                                <th>备注</th>
                            </tr>
                        </thead>
                        <tbody id="processTableBody">
                            <!-- 数据将通过AJAX加载 -->
                        </tbody>
                    </table>
                    
                    <div class="d-flex justify-content-between align-items-center mt-3">
                        <div id="totalProcessInfo">共 0 项数据</div>
                        <div class="d-flex align-items-center">
                            <select id="processPageSizeSelect" class="form-select form-select-sm me-2" style="width: auto;">
                                <option value="5" selected>5条/页</option>
                                <option value="10">10条/页</option>
                                <option value="20">20条/页</option>
                                <option value="50">50条/页</option>
                            </select>
                            <div id="processLaypageContainer"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 操作记录 Tab -->
        <div class="tab-pane fade" id="operation-record" role="tabpanel" aria-labelledby="operation-record-tab">
            <div class="search-export-bar">
                <button id="exportOperationBtn" class="btn btn-primary" onclick="DaochuLog()">导出</button>
                <div class="search-box">
                    <input type="text" id="searchOperationInput" class="form-control" placeholder="请搜索">
                    <button class="btn btn-outline-secondary" type="button" id="searchOperationBtn">
                        <i class="layui-icon layui-icon-search"></i>
                    </button>
                </div>
            </div>
            
            <div class="card">
                <div class="card-body">
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th style="width: 40px;"><input type="checkbox" id="selectAllOperation"></th>
                                <th style="width: 60px;">序号</th>
                                <th>操作人</th>
                                <th>操作时间</th>
                                <th>操作内容</th>
                            </tr>
                        </thead>
                        <tbody id="operationTableBody">
                            <!-- 数据将通过AJAX加载 -->
                        </tbody>
                    </table>
                    
                    <div class="d-flex justify-content-between align-items-center mt-3">
                        <div id="totalOperationInfo">共 0 项数据</div>
                        <div class="d-flex align-items-center">
                            <select id="operationPageSizeSelect" class="form-select form-select-sm me-2" style="width: auto;">
                                <option value="15" selected>15条/页</option>
                                <option value="20">20条/页</option>
                                <option value="25">25条/页</option>
                                <option value="30">30条/页</option>
                            </select>
                            <div id="operationLaypageContainer"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    var currentTab = 'bom-info';
    var currentPage = 1;
    var currentLimit = 15;

    $(function () { 
        Query_Information();
        Query_Accessories();
        Query_Process();
        Query_log();
    })

    //导出操作记录信息
    function DaochuLog() {
        var id = localStorage.getItem("id");
        if (!id) {
            alert('未找到BOM ID，无法导出');
            return;
        }

        // 生成文件名
        var timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
        var fileName = 'BOM操作记录信息_' + timestamp + '.xlsx';

        // 显示加载提示
        var loadingMsg = '正在导出操作记录信息，请稍候...';
        if (typeof layer !== 'undefined') {
            layer.msg(loadingMsg, { icon: 16, time: 0 });
        } else {
            alert(loadingMsg);
        }

        try {
            // 检查是否支持现代文件API
            if (typeof showSaveFilePicker !== 'undefined') {
                // 方法1：使用现代文件API选择保存位置（Chrome 86+）
                modernExportLog(id, fileName);
            } else if (typeof fetch !== 'undefined') {
                // 方法2：使用fetch下载文件（推荐）
                fetchExportLog(id, fileName);
            } else {
                // 方法3：传统下载方法（兼容性最好）
                fallbackExportLog(id, fileName);
            }
        } catch (error) {
            console.error('导出异常:', error);
            // 如果出现异常，回退到传统方法
            fallbackExportLog(id, fileName);
        }

    }
    // 现代文件API导出方法（支持选择保存位置）
    function modernExportLog(id, fileName) {
        fetch('http://localhost:5280/api/WookOrder/GetBOM_LogsModel?Id=' + id)
            .then(response => {
                if (!response.ok) {
                    throw new Error('导出失败: ' + response.status);
                }
                return response.blob();
            })
            .then(async (blob) => {
                try {
                    // 使用现代文件API选择保存位置
                    const fileHandle = await showSaveFilePicker({
                        suggestedName: fileName,
                        types: [{
                            description: 'Excel文件',
                            accept: {
                                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx']
                            }
                        }]
                    });

                    // 写入文件
                    const writable = await fileHandle.createWritable();
                    await writable.write(blob);
                    await writable.close();

                    // 隐藏加载提示并显示成功消息
                    if (typeof layer !== 'undefined') {
                        layer.closeAll();
                        layer.msg('导出完成！文件已保存到您选择的位置', { icon: 1, time: 3000 });
                    } else {
                        alert('导出完成！文件已保存到您选择的位置');
                    }
                } catch (error) {
                    console.error('文件保存失败:', error);
                    if (error.name === 'AbortError') {
                        // 用户取消了文件选择
                        if (typeof layer !== 'undefined') {
                            layer.closeAll();
                            layer.msg('导出已取消', { icon: 0, time: 2000 });
                        } else {
                            alert('导出已取消');
                        }
                    } else {
                        // 其他错误，回退到fetch方法
                        fetchExportLog(id, fileName);
                    }
                }
            })
            .catch(error => {
                console.error('导出错误:', error);
                // 如果fetch失败，回退到传统方法
                fallbackExportLog(id, fileName);
            });
    }

    // Fetch导出方法
    function fetchExportLog(id, fileName) {
        fetch('http://localhost:5280/api/WookOrder/GetBOM_LogsModel?Id=' + id)
            .then(response => {
                if (!response.ok) {
                    throw new Error('导出失败: ' + response.status);
                }
                return response.blob();
            })
            .then(blob => {
                // 创建下载链接
                var url = window.URL.createObjectURL(blob);
                var link = document.createElement('a');
                link.href = url;
                link.download = fileName;
                link.style.display = 'none';

                // 添加到页面并触发下载
                document.body.appendChild(link);
                link.click();

                // 清理
                document.body.removeChild(link);
                window.URL.revokeObjectURL(url);

                // 隐藏加载提示并显示成功消息
                if (typeof layer !== 'undefined') {
                    layer.closeAll();
                    layer.msg('导出完成！文件已保存为: ' + fileName, { icon: 1, time: 3000 });
                } else {
                    alert('导出完成！文件已保存为: ' + fileName);
                }
            })
            .catch(error => {
                console.error('导出错误:', error);
                // 如果fetch失败，回退到传统方法
                fallbackExportLog(id, fileName);
            });
    }

    // 备用导出方法（兼容性最好）
    function fallbackExportLog(id, fileName) {
        try {
            // 创建下载链接
            var downloadUrl = 'http://localhost:5280/api/WookOrder/GetBOM_LogsModel?Id=' + id;

            // 创建隐藏的下载链接
            var link = document.createElement('a');
            link.href = downloadUrl;
            link.download = fileName;
            link.style.display = 'none';
            link.target = '_blank';

            // 添加到页面并触发下载
            document.body.appendChild(link);
            link.click();

            // 延迟清理，确保下载开始
            setTimeout(function () {
                document.body.removeChild(link);
            }, 1000);

            // 隐藏加载提示并显示成功消息
            if (typeof layer !== 'undefined') {
                layer.closeAll();
                layer.msg('导出完成！文件已保存为: ' + fileName, { icon: 1, time: 3000 });
            } else {
                alert('导出完成！文件已保存为: ' + fileName);
            }
        } catch (error) {
            console.error('备用导出方法失败:', error);
            if (typeof layer !== 'undefined') {
                layer.closeAll();
                layer.msg('导出失败: ' + error.message, { icon: 2, time: 3000 });
            } else {
                alert('导出失败: ' + error.message);
            }
        }
    }




    //导出工艺流程信息
    function DaochuProcess() {
        var id = localStorage.getItem("id");
        if (!id) {
            alert('未找到BOM ID，无法导出');
            return;
        }

        // 生成文件名
        var timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
        var fileName = 'BOM工艺流程信息_' + timestamp + '.xlsx';

        // 显示加载提示
        var loadingMsg = '正在导出工艺流程信息，请稍候...';
        if (typeof layer !== 'undefined') {
            layer.msg(loadingMsg, { icon: 16, time: 0 });
        } else {
            alert(loadingMsg);
        }

        try {
            // 检查是否支持现代文件API
            if (typeof showSaveFilePicker !== 'undefined') {
                // 方法1：使用现代文件API选择保存位置（Chrome 86+）
                modernExportProcess(id, fileName);
            } else if (typeof fetch !== 'undefined') {
                // 方法2：使用fetch下载文件（推荐）
                fetchExportProcess(id, fileName);
            } else {
                // 方法3：传统下载方法（兼容性最好）
                fallbackExportProcess(id, fileName);
            }
        } catch (error) {
            console.error('导出异常:', error);
            // 如果出现异常，回退到传统方法
            fallbackExportProcess(id, fileName);
        }

    }
    // 现代文件API导出方法（支持选择保存位置）
    function modernExportProcess(id, fileName) {
        fetch('http://localhost:5280/api/WookOrder/GetProcess?Id=' + id)
            .then(response => {
                if (!response.ok) {
                    throw new Error('导出失败: ' + response.status);
                }
                return response.blob();
            })
            .then(async (blob) => {
                try {
                    // 使用现代文件API选择保存位置
                    const fileHandle = await showSaveFilePicker({
                        suggestedName: fileName,
                        types: [{
                            description: 'Excel文件',
                            accept: {
                                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx']
                            }
                        }]
                    });

                    // 写入文件
                    const writable = await fileHandle.createWritable();
                    await writable.write(blob);
                    await writable.close();

                    // 隐藏加载提示并显示成功消息
                    if (typeof layer !== 'undefined') {
                        layer.closeAll();
                        layer.msg('导出完成！文件已保存到您选择的位置', { icon: 1, time: 3000 });
                    } else {
                        alert('导出完成！文件已保存到您选择的位置');
                    }
                } catch (error) {
                    console.error('文件保存失败:', error);
                    if (error.name === 'AbortError') {
                        // 用户取消了文件选择
                        if (typeof layer !== 'undefined') {
                            layer.closeAll();
                            layer.msg('导出已取消', { icon: 0, time: 2000 });
                        } else {
                            alert('导出已取消');
                        }
                    } else {
                        // 其他错误，回退到fetch方法
                        fetchExportProcess(id, fileName);
                    }
                }
            })
            .catch(error => {
                console.error('导出错误:', error);
                // 如果fetch失败，回退到传统方法
                fallbackExportProcess(id, fileName);
            });
    }

    // Fetch导出方法
    function fetchExportProcess(id, fileName) {
        fetch('http://localhost:5280/api/WookOrder/GetProcess?Id=' + id)
            .then(response => {
                if (!response.ok) {
                    throw new Error('导出失败: ' + response.status);
                }
                return response.blob();
            })
            .then(blob => {
                // 创建下载链接
                var url = window.URL.createObjectURL(blob);
                var link = document.createElement('a');
                link.href = url;
                link.download = fileName;
                link.style.display = 'none';

                // 添加到页面并触发下载
                document.body.appendChild(link);
                link.click();

                // 清理
                document.body.removeChild(link);
                window.URL.revokeObjectURL(url);

                // 隐藏加载提示并显示成功消息
                if (typeof layer !== 'undefined') {
                    layer.closeAll();
                    layer.msg('导出完成！文件已保存为: ' + fileName, { icon: 1, time: 3000 });
                } else {
                    alert('导出完成！文件已保存为: ' + fileName);
                }
            })
            .catch(error => {
                console.error('导出错误:', error);
                // 如果fetch失败，回退到传统方法
                fallbackExportProcess(id, fileName);
            });
    }

    // 备用导出方法（兼容性最好）
    function fallbackExportProcess(id, fileName) {
        try {
            // 创建下载链接
            var downloadUrl = 'http://localhost:5280/api/WookOrder/GetProcess?Id=' + id;

            // 创建隐藏的下载链接
            var link = document.createElement('a');
            link.href = downloadUrl;
            link.download = fileName;
            link.style.display = 'none';
            link.target = '_blank';

            // 添加到页面并触发下载
            document.body.appendChild(link);
            link.click();

            // 延迟清理，确保下载开始
            setTimeout(function () {
                document.body.removeChild(link);
            }, 1000);

            // 隐藏加载提示并显示成功消息
            if (typeof layer !== 'undefined') {
                layer.closeAll();
                layer.msg('导出完成！文件已保存为: ' + fileName, { icon: 1, time: 3000 });
            } else {
                alert('导出完成！文件已保存为: ' + fileName);
            }
        } catch (error) {
            console.error('备用导出方法失败:', error);
            if (typeof layer !== 'undefined') {
                layer.closeAll();
                layer.msg('导出失败: ' + error.message, { icon: 2, time: 3000 });
            } else {
                alert('导出失败: ' + error.message);
            }
        }
    }




    // 导出配件信息
    function DaochuAccessories() {
        var id = localStorage.getItem("id");
        if (!id) {
            alert('未找到BOM ID，无法导出');
            return;
        }
        
        // 生成文件名
        var timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
        var fileName = 'BOM配件信息_' + timestamp + '.xlsx';
        
        // 显示加载提示
        var loadingMsg = '正在导出配件信息，请稍候...';
        if (typeof layer !== 'undefined') {
            layer.msg(loadingMsg, {icon: 16, time: 0});
        } else {
            alert(loadingMsg);
        }
        
        try {
            // 检查是否支持现代文件API
            if (typeof showSaveFilePicker !== 'undefined') {
                // 方法1：使用现代文件API选择保存位置（Chrome 86+）
                modernExportAccessories(id, fileName);
            } else if (typeof fetch !== 'undefined') {
                // 方法2：使用fetch下载文件（推荐）
                fetchExportAccessories(id, fileName);
            } else {
                // 方法3：传统下载方法（兼容性最好）
                fallbackExportAccessories(id, fileName);
            }
        } catch (error) {
            console.error('导出异常:', error);
            // 如果出现异常，回退到传统方法
            fallbackExportAccessories(id, fileName);
        }
    }

    // 现代文件API导出方法（支持选择保存位置）
    function modernExportAccessories(id, fileName) {
        fetch('http://localhost:5280/api/WookOrder/GetAccessories?Id=' + id)
            .then(response => {
                if (!response.ok) {
                    throw new Error('导出失败: ' + response.status);
                }
                return response.blob();
            })
            .then(async (blob) => {
                try {
                    // 使用现代文件API选择保存位置
                    const fileHandle = await showSaveFilePicker({
                        suggestedName: fileName,
                        types: [{
                            description: 'Excel文件',
                            accept: {
                                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx']
                            }
                        }]
                    });
                    
                    // 写入文件
                    const writable = await fileHandle.createWritable();
                    await writable.write(blob);
                    await writable.close();
                    
                    // 隐藏加载提示并显示成功消息
                    if (typeof layer !== 'undefined') {
                        layer.closeAll();
                        layer.msg('导出完成！文件已保存到您选择的位置', {icon: 1, time: 3000});
                    } else {
                        alert('导出完成！文件已保存到您选择的位置');
                    }
                } catch (error) {
                    console.error('文件保存失败:', error);
                    if (error.name === 'AbortError') {
                        // 用户取消了文件选择
                        if (typeof layer !== 'undefined') {
                            layer.closeAll();
                            layer.msg('导出已取消', {icon: 0, time: 2000});
                        } else {
                            alert('导出已取消');
                        }
                    } else {
                        // 其他错误，回退到fetch方法
                        fetchExportAccessories(id, fileName);
                    }
                }
            })
            .catch(error => {
                console.error('导出错误:', error);
                // 如果fetch失败，回退到传统方法
                fallbackExportAccessories(id, fileName);
            });
    }

    // Fetch导出方法
    function fetchExportAccessories(id, fileName) {
        fetch('http://localhost:5280/api/WookOrder/GetAccessories?Id=' + id)
            .then(response => {
                if (!response.ok) {
                    throw new Error('导出失败: ' + response.status);
                }
                return response.blob();
            })
            .then(blob => {
                // 创建下载链接
                var url = window.URL.createObjectURL(blob);
                var link = document.createElement('a');
                link.href = url;
                link.download = fileName;
                link.style.display = 'none';
                
                // 添加到页面并触发下载
                document.body.appendChild(link);
                link.click();
                
                // 清理
                document.body.removeChild(link);
                window.URL.revokeObjectURL(url);
                
                // 隐藏加载提示并显示成功消息
                if (typeof layer !== 'undefined') {
                    layer.closeAll();
                    layer.msg('导出完成！文件已保存为: ' + fileName, {icon: 1, time: 3000});
                } else {
                    alert('导出完成！文件已保存为: ' + fileName);
                }
            })
            .catch(error => {
                console.error('导出错误:', error);
                // 如果fetch失败，回退到传统方法
                fallbackExportAccessories(id, fileName);
            });
    }

    // 备用导出方法（兼容性最好）
    function fallbackExportAccessories(id, fileName) {
        try {
            // 创建下载链接
            var downloadUrl = 'http://localhost:5280/api/WookOrder/GetAccessories?Id=' + id;
            
            // 创建隐藏的下载链接
            var link = document.createElement('a');
            link.href = downloadUrl;
            link.download = fileName;
            link.style.display = 'none';
            link.target = '_blank';
            
            // 添加到页面并触发下载
            document.body.appendChild(link);
            link.click();
            
            // 延迟清理，确保下载开始
            setTimeout(function() {
                document.body.removeChild(link);
            }, 1000);
            
            // 隐藏加载提示并显示成功消息
            if (typeof layer !== 'undefined') {
                layer.closeAll();
                layer.msg('导出完成！文件已保存为: ' + fileName, {icon: 1, time: 3000});
            } else {
                alert('导出完成！文件已保存为: ' + fileName);
            }
        } catch (error) {
            console.error('备用导出方法失败:', error);
            if (typeof layer !== 'undefined') {
                layer.closeAll();
                layer.msg('导出失败: ' + error.message, {icon: 2, time: 3000});
            } else {
                alert('导出失败: ' + error.message);
            }
        }
    }

    function UpdateBom() { 
        var obj = {};

        obj.boM_Number = $("#bomNumber").val();
        obj.default_BOM = $("#defaultBOM").val() === 'true';
        obj.product_Type = $("#productType").val();
        obj.daily_Output = $("#dailyOutput").val();
        obj.notes = $("#remarks").val();
        obj.boM_Theme = $("#bomTheme").val();
        obj.version = $("#version").val();
        obj.product_Name = $("#productName").val();
        obj.id = localStorage.getItem("id");
        
        console.log('发送的数据:', obj);
        
        $.ajax({
            url: 'http://localhost:5280/api/WookOrder/UpdateBasic_InformationHandle',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(obj),
            dataType: 'json',
            success: function(res) {
                console.log('响应结果:', res);
                if (res && res.code === 200) {
                    alert('修改成功');
                    // 刷新数据
                    Query_Information();
                } else {
                    alert('修改失败: ' + (res ? res.msg : '未知错误'));
                }
            },
            error: function(xhr, status, error) {
                console.error('请求失败:', xhr.status, error);
                console.log('响应内容:', xhr.responseText);
                alert('修改失败: ' + error);
            }
        });
    }

    //查询基本信息
    function Query_Information() {
        var id = localStorage.getItem("id");
        if (!id) {
            console.log('未找到ID参数');
            return;
        }
        
        $.ajax({
            url: "http://localhost:5280/api/WookOrder/GetBasic_InformationHandle",
            type: "get",
            data: {Id: id},
            success: function(res) { 
                console.log('API响应(基础信息):', res);
                
                // 优先从 res.data.basic_Information 读取；否则回退到 res.pageData[0]
                var bomData = (res && res.data && res.data.basic_Information)
                    ? res.data.basic_Information
                    : (res && res.pageData && res.pageData.length > 0 ? res.pageData[0] : null);

                if (bomData) {
                    $("#bomNumber").val(bomData.boM_Number || bomData.bom_Number || '');
                    $("#bomTheme").val(bomData.boM_Theme || bomData.bom_Theme || '');
                    $("#defaultBOM").val((bomData.default_BOM === true || bomData.default_BOM === 'true') ? 'true' : 'false');
                    $("#version").val(bomData.version || '');
                    $("#productType").val(bomData.product_Type || '');
                    $("#productName").val(bomData.product_Name || '');
                    $("#dailyOutput").val(bomData.daily_Output || '');
                    $("#remarks").val(bomData.notes || '');

                    $("#pageTitle").text((bomData.boM_Theme || bomData.bom_Theme || 'BOM详情'));
                    console.log('基础信息更新成功');
                } else {
                    console.log('未找到BOM基础信息');
                }
            },
            error: function(xhr, status, error) {
                console.error('获取BOM基础信息失败:', error);
                console.log('响应状态:', xhr.status);
                console.log('响应内容:', xhr.responseText);
            }
        });
    }

    // 查询配件数据
    function Query_Accessories() {
        var id = localStorage.getItem("id");
        if (!id) {
            console.log('未找到ID参数');
            $('#accessoriesTableBody').html('<tr><td colspan="10" class="text-center">未找到ID参数</td></tr>');
            $('#totalAccessoriesInfo').text('共 0 项数据');
            return;
        }

        $.ajax({
            url: "http://localhost:5280/api/WookOrder/GetBasic_InformationHandle",
            type: "get",
            data: { Id: id },
            success: function (res) {
                console.log('配件数据响应:', res);

                var dataObj = (res && res.data) ? res.data : {};
                var bomAccessories = dataObj.boM_Accessories || dataObj.bom_Accessories || [];
                var basicAccessories = dataObj.basic_Accessories || [];

                if (bomAccessories.length > 0 && basicAccessories.length > 0) {
                    var html = '';
                    bomAccessories.forEach(function(item, index){
                        // 从boM_Accessories获取基本信息
                        var rid = item.id || item.Id || item.ID || '';
                        var serial = item.serial_Number || '';
                        var name = item.item_Name || '';
                        var spec = item.specification_Model || '';
                        var unit = item.unit || '';
                        var brand = item.brand || '';
                        
                        // 从basic_Accessories中查找对应的数量信息
                        var basicItem = basicAccessories.find(function(basic) {
                            return basic.accessories_ID === item.id;
                        });
                        
                        var qty = '';
                        var loss = '';
                        if (basicItem) {
                            qty = (basicItem.accessories_Number != null && basicItem.accessories_Number !== '') ? basicItem.accessories_Number : '';
                            loss = (basicItem.attrition_Rate != null && basicItem.attrition_Rate !== '') ? basicItem.attrition_Rate : '';
                        }
                        
                        var serialNo = (currentPage - 1) * currentLimit + index + 1;
                        html += `
                            <tr data-id="${rid}">
                                <td><input type="checkbox" data-id="${rid}"></td>
                                <td>${serialNo}</td>
                                <td>${serial}</td>
                                <td>${name}</td>
                                <td>${spec}</td>
                                <td>${unit}</td>
                                <td>${brand}</td>
                                <td>${qty}</td>
                                <td>${loss}</td>
                                <td><a href="#" class="text-primary">创建子BOM</a></td>
                            </tr>`;
                    });
                    $('#accessoriesTableBody').html(html);
                    $('#totalAccessoriesInfo').text(`共 ${bomAccessories.length} 项数据`);
                    console.log('配件行数:', $('#accessoriesTableBody tr').length);
                } else {
                    $('#accessoriesTableBody').html('<tr><td colspan="10" class="text-center">暂无配件数据</td></tr>');
                    $('#totalAccessoriesInfo').text('共 0 项数据');
                    console.log('未找到配件数据，boM_Accessories:', bomAccessories, 'basic_Accessories:', basicAccessories);
                }
            },
            error: function (xhr, status, error) {
                console.error('获取配件数据失败:', error);
                console.log('响应状态:', xhr.status);
                console.log('响应内容:', xhr.responseText);
                
                $('#accessoriesTableBody').html('<tr><td colspan="10" class="text-center">加载数据失败</td></tr>');
                $('#totalAccessoriesInfo').text('共 0 项数据');
            }
        });
    }


        // 查询工艺数据
    function Query_Process() {
        var id = localStorage.getItem("id");
        if (!id) {
            console.log('未找到ID参数');
            $('#processTableBody').html('<tr><td colspan="8" class="text-center">未找到ID参数</td></tr>');
            $('#totalProcessInfo').text('共 0 项数据');
            return;
        }

        $.ajax({
            url: "http://localhost:5280/api/WookOrder/GetBasic_InformationHandle",
            type: "get",
            data: { Id: id },
            success: function (res) {
                console.log('工艺数据响应:', res);

                var dataObj = (res && res.data) ? res.data : {};
                var processFlow = dataObj.process_Flow || [];
                var basicProcess = dataObj.basic_Process || [];

                if (processFlow.length > 0 && basicProcess.length > 0) {
                    var html = '';
                    processFlow.forEach(function (item, index) {
                        // 从process_Flow获取基本信息
                        var rid = item.id || item.Id || item.ID || '';
                        var processCode = item.process_Code || '';
                        var processName = item.process_Name || '';
                        
                        // 从basic_Process中查找对应的详细信息
                        var basicItem = basicProcess.find(function (basic) {
                            return basic.process_ID === item.id;
                        });

                        var sequence = '';
                        var processFlowDesc = '';
                        var responsible = '';
                        var department = '';
                        var workload = '';
                        var notes = '';
                        
                        if (basicItem) {
                            sequence = (basicItem.processing_Sequence != null && basicItem.processing_Sequence !== '') ? basicItem.processing_Sequence : '';
                            processFlowDesc = (basicItem.process_Flows != null && basicItem.process_Flows !== '') ? basicItem.process_Flows : '';
                            responsible = (basicItem.person_Charge != null && basicItem.person_Charge !== '') ? basicItem.person_Charge : '';
                            department = (basicItem.department != null && basicItem.department !== '') ? basicItem.department : '';
                            workload = (basicItem.unit_Workload != null && basicItem.unit_Workload !== '') ? basicItem.unit_Workload : '';
                            notes = (basicItem.notes != null && basicItem.notes !== '') ? basicItem.notes : '';
                        }

                        var serialNo = (currentPage - 1) * currentLimit + index + 1;
                        html += `
                                <tr data-id="${rid}">
                                    <td><input type="checkbox" data-id="${rid}"></td>
                                    <td>${serialNo}</td>
                                    <td>${processCode}</td>
                                    <td>${processName}</td>
                                    <td>${sequence}</td>
                                    <td>${processFlowDesc}</td>
                                    <td>${responsible}</td>
                                    <td>${department}</td>
                                    <td>${workload}</td>
                                    <td>${notes}</td>
                                </tr>`;
                    });
                    $('#processTableBody').html(html);
                    $('#totalProcessInfo').text(`共 ${processFlow.length} 项数据`);
                    console.log('工艺行数:', $('#processTableBody tr').length);
                } else {
                    $('#processTableBody').html('<tr><td colspan="10" class="text-center">暂无工艺数据</td></tr>');
                    $('#totalProcessInfo').text('共 0 项数据');
                    console.log('未找到工艺数据，process_Flow:', processFlow, 'basic_Process:', basicProcess);
                }
            },
            error: function (xhr, status, error) {
                console.error('获取工艺数据失败:', error);
                console.log('响应状态:', xhr.status);
                console.log('响应内容:', xhr.responseText);

                $('#processTableBody').html('<tr><td colspan="10" class="text-center">加载数据失败</td></tr>');
                $('#totalProcessInfo').text('共 0 项数据');
            }
        });
    }

    //查询操作记录        
    function Query_log() {
        var id = localStorage.getItem("id");
        if (!id) {
            console.log('未找到ID参数');
            $('#operationTableBody').html('<tr><td colspan="4" class="text-center">未找到ID参数</td></tr>');
            $('#totalOperationInfo').text('共 0 项数据');
            return;
        }
        
        $.ajax({
            url: "http://localhost:5280/api/WookOrder/GetBOM_LogsHandle",
            type: "get",
            data: { Id: id },
            success: function (res) {
                console.log('操作记录响应:', res);
                
                var list = (res && res.pageData) ? res.pageData : [];
                
                if (list.length > 0) {
                    var str = '';
                    $(list).each(function (index) {
                        var itemId = this.id || this.Id || this.ID || ''; // 兼容不同大小写
                        var operatorId = this.operator || '';
                        var operation_Time = this.operation_Time || '';
                        var message = this.message || '';
                        
                        // 操作人ID到姓名的映射
                        var operatorName = '';
                        console.log('当前操作人ID:', operatorId, '类型:', typeof operatorId);
                        // 将operatorId转换为字符串进行比较，或者直接使用数字比较
                        switch (Number(operatorId)) {
                            case 10032:
                                operatorName = '吴维昊';
                                break;
                            case 10036:
                                operatorName = '王雨龙';
                                break;
                            case 10037:
                                operatorName = '张可欣';
                                break;
                            case 10038:
                                operatorName = '赵姝雅';
                                break;
                            case 10039:
                                operatorName = '段栋兴';
                                break;
                            default:
                                operatorName = operatorId; // 如果没有匹配的ID，显示原始ID
                        }
                        console.log('映射后的姓名:', operatorName);
                        
                        // 格式化时间显示
                        var formattedTime = '';
                        if (operation_Time) {
                            try {
                                var date = new Date(operation_Time);
                                formattedTime = date.toLocaleString('zh-CN');
                            } catch (e) {
                                formattedTime = operation_Time;
                            }
                        }
                        
                        var serialNo = index + 1;
                        str += `<tr data-id="${itemId}">
                                    <td><input type="checkbox" data-id="${itemId}"></td>
                                    <td>${serialNo}</td>
                                    <td>${operatorName}</td>
                                    <td>${formattedTime}</td>
                                    <td>${message}</td>
                                </tr>`;
                    });
                    
                    $("#operationTableBody").html(str);
                    $('#totalOperationInfo').text(`共 ${list.length} 项数据`);
                    console.log('操作记录行数:', $('#operationTableBody tr').length);
                } else {
                    $("#operationTableBody").html('<tr><td colspan="5" class="text-center">暂无操作记录</td></tr>');
                    $('#totalOperationInfo').text('共 0 项数据');
                }
                
                $('#checkAllProcess').prop('checked', false);
            },
            error: function (xhr) {
                console.error('加载操作记录列表失败:', xhr.status, xhr.responseText);
                $("#operationTableBody").html('<tr><td colspan="5" class="text-center">加载失败</td></tr>');
                $('#totalOperationInfo').text('共 0 项数据');
            }
        });
    }


    $(document).ready(function () {
        // 初始化页面
        loadBomInfo();
        
        // 标签页切换事件
        $('#bomTabs button[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
            currentTab = e.target.id.replace('-tab', '');
            currentPage = 1;
            currentLimit = 5;
            
            switch(currentTab) {
                case 'bom-info':
                    loadBomInfo();
                    break;
                case 'bom-accessories':
                    loadBomAccessories();
                    break;
                case 'process-flow':
                    loadProcessFlow();
                    break;
                case 'operation-record':
                    loadOperationRecord();
                    break;
            }
        });

        // 搜索事件
        $('#searchAccessoriesBtn').on('click', function() {
            loadBomAccessories();
        });

        $('#searchProcessBtn').on('click', function() {
            loadProcessFlow();
        });

        $('#searchOperationBtn').on('click', function() {
            loadOperationRecord();
        });

        // 分页大小改变事件
        $('#accessoriesPageSizeSelect').on('change', function() {
            currentLimit = parseInt($(this).val());
            currentPage = 1;
            loadBomAccessories();
        });

        $('#processPageSizeSelect').on('change', function() {
            currentLimit = parseInt($(this).val());
            currentPage = 1;
            loadProcessFlow();
        });

        $('#operationPageSizeSelect').on('change', function() {
            currentLimit = parseInt($(this).val());
            currentPage = 1;
            loadOperationRecord();
        });

        // 全选事件
        $('#selectAllAccessories').on('change', function() {
            $('#accessoriesTableBody input[type="checkbox"]').prop('checked', $(this).prop('checked'));
        });

        $('#selectAllProcess').on('change', function() {
            $('#processTableBody input[type="checkbox"]').prop('checked', $(this).prop('checked'));
        });

        $('#selectAllOperation').on('change', function() {
            $('#operationTableBody input[type="checkbox"]').prop('checked', $(this).prop('checked'));
        });

        // 导出按钮的事件在各自的 onclick 中实现，这里不再绑定占位事件
    });

    // 加载BOM信息
    function loadBomInfo() {
     
    }

    // 加载BOM配件
    function loadBomAccessories() {
        // 使用实际接口查询
        Query_Accessories();
    }

    // 加载工艺流程
    function loadProcessFlow() {
        Query_Process();
    }

    // 加载操作记录
    function loadOperationRecord() {
        Query_log();
    }

    // // 渲染配件表格
    // function renderAccessoriesTable(data) {
    //     var html = '';
    //     data.forEach(function(item, index) 
    //     {
    //         var serialNo = (currentPage - 1) * currentLimit + index + 1;
    //         html += `
    //             <tr>
    //                 <td><input type="checkbox" data-id="${item.id}"></td>
    //                 <td>${serialNo}</td>
    //                 <td>${item.itemNumber}</td>
    //                 <td>${item.itemName}</td>
    //                 <td>${item.spec}</td>
    //                 <td>${item.unit}</td>
    //                 <td>${item.brand}</td>
    //                 <td>${item.quantity}</td>
    //                 <td>${item.lossRate}</td>
    //                 <td>${item.currentStock}</td>
    //                 <td>${item.availableForProduction}</td>
    //                 <td><a href="#" class="text-primary">创建子BOM</a></td>
    //             </tr>
    //         `;
    //     });
    //     $('#accessoriesTableBody').html(html);
    //     $('#totalAccessoriesInfo').text(`共 ${data.length} 项数据`);
    // }

    // 渲染工艺流程表格
    function renderProcessTable(data) {
        var html = '';
        data.forEach(function(item, index) {
            var serialNo = (currentPage - 1) * currentLimit + index + 1;
            html += `
                <tr>
                    <td><input type="checkbox" data-id="${item.id}"></td>
                    <td>${serialNo}</td>
                    <td>${item.processCode}</td>
                    <td>${item.processName}</td>
                    <td>${item.sequence}</td>
                    <td>${item.processFlow}</td>
                    <td>${item.responsible}</td>
                    <td>${item.department}</td>
                    <td>${item.workload}</td>
                </tr>
            `;
        });
        $('#processTableBody').html(html);
        $('#totalProcessInfo').text(`共 ${data.length} 项数据`);
    }

    // 渲染操作记录表格
    function renderOperationTable(data) {
        var html = '';
        data.forEach(function(item, index) {
            var serialNo = (currentPage - 1) * currentLimit + index + 1;
            html += `
                <tr>
                    <td><input type="checkbox" data-id="${item.id}"></td>
                    <td>${serialNo}</td>
                    <td>${item.operator}</td>
                    <td>${item.operationTime}</td>
                    <td>${item.operationContent}</td>
                </tr>
            `;
        });
        $('#operationTableBody').html(html);
        $('#totalOperationInfo').text(`共 ${data.length} 项数据`);
    }

    // 渲染分页
    function renderPagination(type, totalCount) {
        layui.use(['laypage'], function() {
            var laypage = layui.laypage;
            
            laypage.render({
                elem: `#${type}LaypageContainer`,
                count: totalCount,
                limit: currentLimit,
                curr: currentPage,
                layout: ['prev', 'page', 'next', 'skip'],
                jump: function(obj, first) {
                    if (!first) {
                        currentPage = obj.curr;
                        currentLimit = obj.limit;
                        
                        switch(type) {
                            case 'accessories':
                                loadBomAccessories();
                                break;
                            case 'process':
                                loadProcessFlow();
                                break;
                            case 'operation':
                                loadOperationRecord();
                                break;
                        }
                    }
                }
            });
        });
    }


</script>

